<?php

	function load_current_user()
  {
    foreach (explode("\n", trim(INSECURE_MODULES)) as $module) {
    	$_SESSION['current_user']['permissions']['modules'][$module] = true;
    }

    $_SESSION['current_user'] = db_select($_SESSION['current_user']['id'], 'users', true);

		//get default access rights (for everone!)
 		$sql = "SELECT * FROM user_roles_data_access WHERE user_roles_id = 0";
		$qryp = db_query($sql);
    while ($p = db_fetch_assoc($qryp)) {
    	$_SESSION['current_user']['data_access'][$p['table_name']][$p['action']] = true;
    }

 		$sql = "SELECT * FROM user_roles_module_access WHERE user_roles_id = 0";
		$qryp = db_query($sql);
    while ($p = db_fetch_assoc($qryp)) {
			$p['module'] = db_field($p['modules_id'], 'modules', 'folder', true);
    	$_SESSION['current_user']['module_access'][$p['module']][$p['file']] = true;
    }

	 	//get access rights for assigned roles
	 	if ($_SESSION['current_user']['id'] !== 0) {
      $sql = "SELECT * FROM user_roles WHERE id IN (SELECT user_roles_id FROM users_to_user_roles WHERE users_id = {$_SESSION['current_user']['id']}) ORDER BY id ASC";
      $qry = db_query($sql);
      while ($user_role = db_fetch_assoc($qry)) {
      	$_SESSION['current_user']['user_roles'][$user_role['id']] = $user_role;

     		$sql = "SELECT * FROM user_roles_data_access WHERE user_roles_id = {$user_role['id']}";
    		$qryp = db_query($sql);
        while ($p = db_fetch_assoc($qryp)) {
        	$_SESSION['current_user']['data_access'][$p['table_name']][$p['action']] = true;
        }

     		$sql = "SELECT * FROM user_roles_module_access WHERE user_roles_id = {$user_role['id']}";
    		$qryp = db_query($sql);
        while ($p = db_fetch_assoc($qryp)) {
					$p['module'] = db_field($p['modules_id'], 'modules', 'folder', true);
        	$_SESSION['current_user']['module_access'][$p['module']][$p['file']] = true;
        }
      }
		}
  }


  function load_module($module = false, $file = false, $params = false)
  {
		if (empty($params)) $params = array();

		//is content from a page or a module?
  	if (empty($module)) $module = $_REQUEST['module'];
    if (empty($module)) $module = $GLOBALS['uri']['module'];

    if (empty($file)) $file = $GLOBALS['uri']['file'];
    if (empty($file)) $file = 'index';

		//see if module is active
		if (db_result(db_query("SELECT active FROM modules WHERE folder = '$module'"), 0) == 0) {
			//module is marked in-active
			echo (is_admin()) ? "<h1>Module: $module is not activated!</h1>" : "\n\n<!-- Module: $module is not activated... -->\n\n";
			return true;
		}
		
  	//see if it exists
    if (!file_exists(PHPDRIVER . "modules/$module/{$file}.php")) {
    	error("Failed to load module! [module=$module&file=$file]");
			return false;
    }

  	//check perms
    if (!authorized($module, $file)) {
			if (stristr($_SERVER['REQUEST_URI'], '/admin/')) {
				if (logged_in()) {
					warning('You do not have permission to access this area.');
					location();
				} else {
					message('Please login to access this area.');
					location('/login.html');
				}
    	} elseif (PARANOID === false) error("You do not have permission to use this module. [module=$module&file=$file]");
			elseif (!logged_in()) load_module('users', 'login');
			else location('/401.html');

			return false;
    }

		echo "\n\n\n\n";
    include PHPDRIVER . "modules/$module/{$file}.php";
		echo "\n\n\n\n";
  }



	function load_page($pages_id = false)
	{
		if ($pages_id === false) $pages_id = $GLOBALS['uri']['pages_id'];

		//load the page based on the pages_id in the url.
  	$sql = "SELECT * FROM pages WHERE id = $pages_id AND published = 1";
  	$qry = db_query($sql);
  	if (db_num_rows($qry) == 0) $page = db_select(-404, 'pages', true);
  	else $page = db_fetch_assoc($qry);

    //check access rights
    if ($page['private'] == 1 && !admin()) {
			if (!logged_in()) {
				load_module('users', 'login');
				return;
			} else {
				if (!admin()) {
      		$sql = "SELECT COUNT(1) FROM pages_to_users WHERE pages_id = $pages_id AND users_id = {$_SESSION['current_user']['id']}";
    			if (db_result(db_query($sql), 0) == 0) {
    				$sql = "SELECT COUNT(1) FROM pages_to_user_roles WHERE pages_id = $pages_id AND user_roles_id IN (SELECT roles_id FROM users_to_user_roles WHERE users_id = {$_SESSION['current_user']['id']})";
      			$qry = db_query($sql);
    				if (db_result(db_query($sql), 0) == 0) location('/401.html');
    			}
				}
  		}
		}

  	foreach (explode("\n", trim($page['content'])) as $query_string) {
			$module = $file = '';
			$params = array();

			foreach (explode('&', trim($query_string)) as $item) {
				list($k, $v) = explode('=', $item);
				if ($k == 'module') $module = $v;
				elseif ($k == 'file') $file = $v;
				else $params[$k] = $v;
			}

			$params['pages_id'] = $page['id'];

			load_module($module, $file, $params);
		}
	}



	function load_theme($theme = false)
	{
		if (empty($theme)) $theme = THEME;

		//see if this is an admin page...
		if (stristr($_SERVER['REQUEST_URI'], '/admin/')) {
			//check perms.
			if (!authorized('/admin/conf/index')) location('/401.html');
			$theme = 'admin';
		} else $page_theme_file = db_field($GLOBALS['uri']['pages_id'], 'pages', 'theme_file', true);

		if (file_exists(PHPDRIVER . "themes/$theme/{$page_theme_file}.php")) require_once PHPDRIVER . "themes/$theme/{$page_theme_file}.php";
  	elseif (file_exists(PHPDRIVER . "themes/$theme/{$GLOBALS['uri']['module']}/{$GLOBALS['uri']['file']}.php")) require_once PHPDRIVER . "themes/$theme/{$GLOBALS['uri']['module']}/{$GLOBALS['uri']['file']}.php";
  	elseif (file_exists(PHPDRIVER . "themes/$theme/{$GLOBALS['uri']['module']}/index.php")) require_once PHPDRIVER . "themes/$theme/{$GLOBALS['uri']['module']}/index.php";
  	elseif (file_exists(PHPDRIVER . "themes/$theme/index.php")) require_once PHPDRIVER . "themes/$theme/index.php";
  	else error('The theme ran away!');
	}



	function load_uri($request_uri = false)
	{
  	#auto-detect request_uri
  	if (empty($request_uri)) $request_uri = (stristr($_SERVER['REQUEST_URI'], '?')) ? substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) : $_SERVER['REQUEST_URI'];
  	//echo pre($request_uri);

		if ($request_uri == '/' && (isset($_REQUEST['module']) || isset($_REQUEST['file'])) ) {
			#old style urls /?module=&file=pages_id=
			#1. check if this is an old-style (deprecated) uri
			$GLOBALS['uri']['module'] = (empty($_REQUEST['module'])) ? 'pages' : $_REQUEST['module'];
			$GLOBALS['uri']['file'] = (empty($_REQUEST['file'])) ? 'index' : $_REQUEST['file'];
		} else {
			#mod_rewrite URLS...
			#2. check for a page with this mod_rewrite uri
    	$sql = "SELECT id FROM pages WHERE uri = '$request_uri'";
    	$qry = db_query($sql);
    	if (db_num_rows($qry) == 1) {
  			$GLOBALS['uri']['module'] = 'pages';
  			$GLOBALS['uri']['file'] = 'index';
  			$GLOBALS['uri']['pages_id'] = db_result($qry, 0);
    	} else {
			#3. see if we are trying to load a module
				$module = trim($request_uri, '/');
				$parts = explode('/', $module);
				$file = ($parts[0] == 'admin') ? array_shift($parts) : '';
				$module = array_shift($parts);
				foreach ($parts as $part) {
					$file.= "/$part";
				}
				$file = trim($file, '/');

				if (file_exists(PHPDRIVER . "modules/$module/{$file}.php")) {
					$GLOBALS['uri']['module'] = $module;
					$GLOBALS['uri']['file'] = $file;
				} else {
			#4. just fail to a 404 page -- we clearly don't know what they are looking for!
					header("HTTP/1.0 404 Not Found");
					header("Status: 404 Not Found");
					if (db_record_exists(-404, 'pages')) {
  					$GLOBALS['uri']['module'] = 'pages';
  					$GLOBALS['uri']['file'] = 'index';
  					$GLOBALS['uri']['pages_id'] = -404;
					} else error("Invalid uri: $request_uri");
					return false;
				}
			}
		}

		#force login, join, or reset pass for non-authenticated users visiting private websites
		if (PRIVATE_WEBSITE === true && !logged_in()) {
			$GLOBALS['uri']['module'] = 'pages';
			$GLOBALS['uri']['file'] = 'index';
			if (!in_array($GLOBALS['uri']['pages_id'], array(-2,-3,-4,-5,-6))) $GLOBALS['uri']['pages_id'] = -3;
		}

		#default pages_id to _REQUEST['pages_id']
		if (empty($GLOBALS['uri']['pages_id'])) $GLOBALS['uri']['pages_id'] = $_REQUEST['pages_id'];
	}



  function local_post($paranoid = false)
  {
  	$protocol = (https()) ? 'https' : 'http';

  	#echo $_SERVER['HTTP_REFERER'] . ' vs. ' . "{$protocol}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";

  	if (!$_POST || count($_POST['login']) == 2) return false;
  	elseif ($paranoid) {
  		if (stristr($_SERVER['HTTP_REFERER'], '?')) {
  			return (stristr($_SERVER['REQUEST_URI'], '?'))
  				? substr($_SERVER['HTTP_REFERER'], 0, strpos($_SERVER['HTTP_REFERER'], '?')) == "{$protocol}://{$_SERVER['HTTP_HOST']}" . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'))
  				: substr($_SERVER['HTTP_REFERER'], 0, strpos($_SERVER['HTTP_REFERER'], '?')) == "{$protocol}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
  		} else {
  			return (stristr($_SERVER['REQUEST_URI'], '?'))
  				? $_SERVER['HTTP_REFERER'] == "{$protocol}://{$_SERVER['HTTP_HOST']}" . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'))
  				: $_SERVER['HTTP_REFERER'] == "{$protocol}://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
  		}
  	} elseif (!stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) {
  		#error("Invalid form submission.<br />{$_SERVER['HTTP_REFERER']} NOT FOUND IN {$_SERVER['HTTP_REFERER']}");
  		return false;
  	} else return true;
  }



	function location($uri = '/')
	{
		#prevent infinite loops!
		if ($uri == $_SESSION['last_location']) return true;
		$_SESSION['last_location'] = $uri;

		if (DEBUG === true) {
			echo "Location: $uri<br />";
		} else {
			header("Location: $uri\r\n");
			exit;
		}
	}



	function logged_in()
	{
		return intval($_SESSION['current_user']['id']) != 0;
	}



	function logout()
	{
		unset($_SESSION['current_user']);//kill current user session
		load_current_user();//reset to guest user.
	}